/*
 * @Author: ChunLai
 * @Date: 2021-12-30 14:54:17
 * @LastEditTime: 2025-09-08 17:17:24
 * @Description: 投/被保人告知详情页
 * @FilePath: \02.bldinsure\src\views\healthy\detail_mx.js
 */
import { mapGetters } from "vuex";
import {
  validateHealthRule,
  pageToApi,
  apiToPageData,
} from "@/translate/healthy/common.js";

export const detailMixin = {
  data() {
    return {
      showPopup: false, // 代理人声明弹出框
      baseConfig: "",
      pageData: {},
      queryData: null, // 路由数据
      utype: "",
      tbName: "",
      bbName: "",
    };
  },
  computed: {
    ...mapGetters({
      riskRelateNotice: "page/riskRelateNotice",
      isFiristBill: "page/isFiristBill",
      firstBillRelateCode: "page/firstBillRelateCode",
      healthyTips: "dictionary/healthyTips",
      showedRisks: "risks/showedRisks",
      apiBbrMult: "insert/apiBbrMult",
      applicant: "insert/applicant",
    }),
    isSameToApplicant() {
      return this.apiBbrMult[this.bbrIdx].relationToAppnt == "4";
    },
    tipMsg() {
      let resMsg =
        "为了保证被保险人的保险权益在理赔时不受影响，请确认uname的身体状况是否符合投保条件";
      /* === 2.配置头部提示信息 === */
      if (this.healthyTips) {
        resMsg = this.healthyTips;
      } else {
        resMsg = resMsg.replace("uname", this.utypeName);
      }
      return resMsg;
    },
    isShareHealthy() {
      let res = false;
      if (this.$getDataFromUrl("share") == "1") {
        res = true;
      }
      return res;
    },
  },
  methods: {
    async dataEcho() {
      let params = {
        ...this.apiComParams,
        type: this.submitType,
      };
      if (this.utype == "bbr") {
        params.idNum = this.apiBbrMult[this.bbrIdx].idNum;
      }
      await this.$store
        .dispatch("apis/comAdminApiRequest", {
          apiParams: params,
          apiName: "queryImparts",
        })
        .then(async (data) => {
          await apiToPageData(this.pageData, data.imparts);
        });
    },
    /* ===== 页面用户操作 ===== */
    setBtnValue(index, idx, value, unit) {
      this.$set(
        this.pageData[index].questionsList[idx],
        "impartYesOrNo",
        value
      );
      /*合众 subjectLimit*/
      if (unit.subjectLimit) {
        const lenVal = this.pageData[index].questionsList.length;
        for (let i = 0; i < lenVal; i++) {
          const queItem = this.pageData[index].questionsList[i];
          if (unit.subjectLimit.includes(queItem.impartCode)) {
            queItem.isHide = value === "0";
          }
        }
      }
      if (value == "0") {
        this.pageData[index].questionsList[idx].answerValue = "";
        this.pageData[index].questionsList[idx].answer.forEach((ele) => {
          ele.value = "";
        });
      }
    },
    setCheckboxs(index, idx, j, itemObj) {
      // console.log(this.pageData[index].questionsList[idx])
      /*合众 showHideKey*/
      if (itemObj.showHideKey) {
        const findQues = this.pageData[index].questionsList[idx].answer,
          findIndex = findQues.findIndex(
            (ele) => ele.ansType === itemObj.showHideKey || ""
          );
        this.$set(
          this.pageData[index].questionsList[idx].answer[findIndex],
          "isHide",
          itemObj.showHideValue === "hide"
        );
        if (["2", "N"].includes(itemObj.value)) {
          this.$set(
            this.pageData[index].questionsList[idx].answer[findIndex],
            "value",
            ""
          );
        }
      }
      this.$set(
        this.pageData[index].questionsList[idx].answer[j],
        "value",
        itemObj.value
      );
    },
    // 多选
    setMultiChecs(index, idx, j, itemObj) {
      const oldVal =
        this.pageData[index].questionsList[idx].answer[j].value || "";
      // console.log('1---', oldVal);
      let newVal = "";
      if (oldVal.indexOf(itemObj.value) == -1) {
        newVal = `${oldVal}${itemObj.value}`;
      } else {
        newVal = oldVal.replace(`${itemObj.value}`, "");
      }
      this.$set(
        this.pageData[index].questionsList[idx].answer[j],
        "value",
        newVal
      );
    },
    setRadioboxs(index, idx, j, itemObj) {
      this.$set(
        this.pageData[index].questionsList[idx].answer[j],
        "value",
        itemObj.value
      );
    },
    formatRule(e, type) {
      // console.log(e.target)
    },
    validInfo(ele) {
      // console.log(ele.label)
      if (ele.validName == "income") {
        if (ele.value > 100) {
          this.$toast("年收入超过100万，可能需要提供收入证明，请确认");
        }
      }
      // console.log(ele)
    },
    /* ===== 数据存储api ===== */
    async nextStep() {
      if (this.disabledEdit) {
        this.$backRouter();
        return;
      }
      // 告知内容校验
      let result = await this.validateBase(this.pageData);
      if (!result) {
        return false;
      }
      // 数据拼接处理
      let apiDatas = await pageToApi(this.pageData);
      /*subjectLimit 过滤校验---待定*/
      // console.log('nextStep---2', apiDatas);
      // return;
      this.nextBeforeConfirm(apiDatas);
    },
    nextBeforeConfirm(apiDatas) {
      // console.log("")
      this.$dialog
        .confirm({
          title: "温馨提示",
          message: `以上内容是否为${
            this.isApplicant ? "投保人本人" : "被保人本人"
          }填写？`,
          confirmButtonColor: "rgb(218, 37, 30)",
        })
        .then(() => {
          this.nextSureClick(apiDatas);
        })
        .catch(() => {});
    },
    async nextSureClick(apiDatas) {
      this.$store.dispatch("common/checkNoticeStatus", apiDatas);
      if (this.isSameToApplicant) {
        // 投保人和被保人是同一人
        try {
          const res1 = await this.submitParmars(apiDatas, "2");
          const res2 = await this.submitParmars(apiDatas, "1");
          this.$store.commit("updateLoad", false);
          if (res1.code === "1" && res2.code === "1") {
            this.apiNextStep();
          }
        } catch (err) {
          this.$store.commit("updateLoad", false);
          console.log(err, "错误");
        }
      } else {
        this.submitParmars(apiDatas, this.submitType).then((data) => {
          this.$store.commit("updateLoad", false);
          if (data.code === "1") {
            this.apiNextStep();
          }
        });
      }
    },
    apiNextStep() {
      if (this.isShareHealthy) {
        this.$router.replace({
          path: "/shareres?res=success",
        });
      } else {
        this.$backRouter();
      }
    },
    async submitParmars(dataList, type) {
      // 预定义参数
      let params = {
        ...this.apiComParams,
        type: type,
        imparts: dataList,
      };
      if (this.utype == "bbr") {
        params.idNum = this.apiBbrMult[this.bbrIdx].idNum;
      }
      // console.log('接口数据', dataList);
      this.$store.commit("updateLoad", true);
      return await this.$store.dispatch("apis/comAdminApiRequest", {
        apiParams: params,
        apiName: "saveImparts",
        toast: true,
      });
    },
    /* ===== 数据规则校验 ===== */
    validateBase(healthyDatas) {
      // console.log('1---', healthyDatas);
      return new Promise((resolve, reject) => {
        let resObj = {};
        for (let i = 0; i < healthyDatas.length; i++) {
          const item = healthyDatas[i];
          resObj = validateHealthRule(item);
          if (!resObj.status) {
            break;
          }
        }
        if (!resObj.status) {
          this.$baseAlert(resObj.msg, () => {
            this.$GlobalFuns.removeToViewEle(resObj.idx);
            resolve(resObj.status);
          });
        } else {
          resolve(true);
        }
      });
    },
  },
};
